type Options = {
  url: string
  method?: 'get' | 'GET' | 'post' | 'POST',
  data: XMLHttpRequestBodyInit
  headers?: Record<string, any>
  onProgress?: (e: ProgressEvent) => void
}

export const request = async (options: Options): Promise<{ data: any }> => {
  return new Promise(resolve => {
    const { url, method = 'get', data, headers } = options
    const xhr = new XMLHttpRequest()
    if (options.onProgress) {
      xhr.upload.onprogress = options.onProgress
    }
    xhr.open(method, url)
    if (headers) {
      Object.keys(headers).forEach(key => {
        xhr.setRequestHeader(key, headers[key])
      })
    }
    xhr.send(data)
    xhr.onload = e => {
      resolve({
        data: (e.target as XMLHttpRequest).response
      })
    }
  })
}